var clickObjId = "#index_home";
var userId, roleId;
var firstLoad = [true, true, true, true, true, true, true];
$(document).ready(function() {

	$('.w li').click(function () {
		$('.w li').removeClass('active');
		$(this).addClass('active');
		var index = $(this).data('index');
		$('.animsition .page:not(.' + index + ')').fadeOut(1, function () {

        });
        $('.animsition .' + index).fadeIn(function () {
            if (index == 7) {
                if (firstLoad[6]) {
                    firstLoad[6] = false;
                    initTree(function () {
                        if ($('#index_pjkh .pageContent.right .contentTitle .contentTag:nth-child(2)').hasClass("active")) {
                            showDevInfo(getCurrentLevel());
                        } else {
                            $('#index_pjkh .pageContent.right .contentBody .addDev .currentLocation .clContent').text(getCurrentLevel()? getCurrentLevel().fullName: "");
                        }
                    }, function () {
                        console.log("Initing tree success!");
                    }, function () {
                        alert("Initing tree failed!");
                    });
                    $('#index_pjkh .pageContent.right .contentTitle .contentTag').click(function () {
                        $('#index_pjkh .pageContent.right .contentTitle .contentTag').removeClass('active');
                        $(this).addClass('active');
                        $('#index_pjkh .pageContent.right .contentBody .devInfo, #index_pjkh .pageContent.right .contentBody .addDev').css("display", "none");
                        var tagIndex = $(this).data('index');
                        if (tagIndex == 1) {
                            $('#index_pjkh .pageContent.right .contentBody .devInfo').fadeIn(function () {
                                $('#index_pjkh .pageContent.right .contentBody .devInfo .currentLocation .clContent').text(getCurrentLevel()? getCurrentLevel().fullName: "");
                                $("#devInfoForm .save").attr("disabled", "disabled");
                            });
                        } else {
                            $('#index_pjkh .pageContent.right .contentBody .addDev').fadeIn(function () {
                                $('#index_pjkh .pageContent.right .contentBody .addDev .currentLocation .clContent').text(getCurrentLevel()? getCurrentLevel().fullName: "");
                                $("#addDevForm .add").attr("disabled", "disabled");
                            });
                        }
                    });
                    //devInfoForm
                    $("#devInfoForm input[type=radio][name=unitOrdep]").on("change", function () {
                        $("#devInfoForm .save").removeAttr("disabled");
                    });
                    $("#devInfoForm .devComment").on("change", function () {
                        $("#devInfoForm .save").removeAttr("disabled");
                    });
                    $("#devInfoForm .devName").on("input", function () {
                        if ($(this).val() == "") {
                            $("#devInfoForm .save").attr("disabled", "disabled");
                        } else {
                            $("#devInfoForm .save").removeAttr("disabled");
                        }
                    });
                    initDialogDefault("#devInfoForm .delete", ".simpleDialog.deleteDialog", function () {
                        deleteDep(function () {
                            if ($('#index_pjkh .pageContent.right .contentTitle .contentTag:nth-child(2)').hasClass("active")) {
                                showDevInfo(getCurrentLevel());
                            } else {
                                $('#index_pjkh .pageContent.right .contentBody .addDev .currentLocation .clContent').text(getCurrentLevel()? getCurrentLevel().fullName: "");
                            }
                        }, function () {
                            resultDialog(true, ".simpleDialog.deleteDialog", function () {
                                //清空填写的数据
                                $("#devInfoForm .devComment").val("");
                                $("#devInfoForm .devName").val("");
                                $('#index_pjkh .pageContent.right .contentBody .devInfo .currentLocation .clContent').text("");
                            });
                        }, function () {
                            resultDialog(false, ".simpleDialog.deleteDialog", function () {
                                console.log("deleteDep/initTree failed.");
                            });
                        })
                    });
                    initDialogDefault("#devInfoForm .save", ".simpleDialog.saveDialog", function () {
                        var level = getCurrentLevel();
                        var isDep = $("#devInfoForm input[type=radio][name=unitOrdep]:checked").val();
                        var department = {
                            name:  $("#devInfoForm .devName").val(),
                            comment:  $("#devInfoForm .devComment").val(),
                            isDep: isDep,
                            level: level
                        };
                        if (department.name == "" || (isDep != 0 && isDep != 1) || department.level == null) {
                            resultDialog(false, ".simpleDialog.saveDialog", function () {
                               console.log("Deleting failed, info is not complete");
                            });
                        } else {
                            updateDep(department, function () {
                                if ($('#index_pjkh .pageContent.right .contentTitle .contentTag:nth-child(2)').hasClass("active")) {
                                    showDevInfo(getCurrentLevel());
                                } else {
                                    $('#index_pjkh .pageContent.right .contentBody .addDev .currentLocation .clContent').text(getCurrentLevel()? getCurrentLevel().fullName: "");
                                }
                            }, function () {
                                resultDialog(true, ".simpleDialog.saveDialog", function () {
                                   showDevInfo(getCurrentLevel());
                                });
                            }, function () {
                                resultDialog(false, ".simpleDialog.saveDialog", function () {
                                    console.log("updateDep/initTree failed.");
                                });
                            });
                        }
                    });
                    //addDevForm
                    $("#addDevForm input[type=radio][name=unitOrdep]").on("change", function () {
                        $("#addDevForm .add").removeAttr("disabled");
                    });
                    $("#addDevForm .devName").on("input", function () {
                        if ($(this).val() == "") {
                            $("#addDevForm .add").attr("disabled", "disabled");
                        } else {
                            $("#addDevForm .add").removeAttr("disabled");
                        }
                    });
                    initDialogDefault("#addDevForm .add", ".simpleDialog.addDialog", function () {
                        var level = getCurrentLevel();
                        var isDep = $("#addDevForm input[type=radio][name=unitOrdep]:checked").val();
                        var department = {
                            name:  $("#addDevForm .devName").val(),
                            comment:  $("#addDevForm .devComment").val(),
                            isDep: isDep,
                            level: level
                        };
                        if (department.name == "" || (isDep != 0 && isDep != 1) || department.level == null) {
                            resultDialog(false, ".simpleDialog.addDialog", function () {
                                console.log("Info is not complete.");
                            });
                        } else {
                            insertDep(department, function () {
                                if ($('#index_pjkh .pageContent.right .contentTitle .contentTag:nth-child(2)').hasClass("active")) {
                                    showDevInfo(getCurrentLevel());
                                } else {
                                    $('#index_pjkh .pageContent.right .contentBody .addDev .currentLocation .clContent').text(getCurrentLevel()? getCurrentLevel().fullName: "");
                                }
                            }, function () {
                                resultDialog(false, ".simpleDialog.addDialog", function () {
                                    console.log("deleteDep/initTree failed.");
                                });
                            }, function () {
                                resultDialog(true, ".simpleDialog.addDialog", function () {
                                    $("#addDevForm .devName").val("");
                                    $("#addDevForm .devComment").val("");
                                    $('#index_pjkh .pageContent.right .contentBody .addDev .currentLocation .clContent').text("");
                                });
                            });
                        }
                    });
                }
                $('#index_pjkh .pageContent.right .contentTitle .contentTag:nth-child(2)').trigger("click");
            }
        });
    });

    $('.w li:nth-child(1)').click();
    initPage4Sidebar();
	showIndexBdly();
	showIndexZrly();
	showIndexZrbm();
});
//根据id查询当前点击的部门的详细信息
function showDevInfo(level) {
    if (level) {
        $('#index_pjkh .pageContent.right .contentBody .devInfo .currentLocation .clContent').text(level.fullName);
        $.ajax({
            type: 'POST',
            url: mmssm_url + 'department/id',
            // async: false,
            dataType: 'json',
            data: "id=" + level.currentId,
        }).done(function (data) {
            if ($('#index_pjkh .pageContent.right .contentTitle .contentTag:nth-child(2)').hasClass('active')) {
                $("#devInfoForm .devName").val(data.name);
                if (data.isDep == 0) {
                    $("#devInfoForm .unitOrdep label:nth-child(1) input").click();
                } else {
                    $("#devInfoForm .unitOrdep label:nth-child(2) input").click();
                }
                $("#devInfoForm .devComment").val(data.comment);
            }
            console.log(data);
        }).fail(function () {
            console.log("Error!");
        });
    } else {
        console.log("No development selected!");
    }
}
function initPage4Sidebar() {
	$('#index_fbjh li a').click(function () {
        var index = $(this).data('index');
        $('#index_fbjh .page-content .container-fluid .nbxc').css('display', 'none');
        $('#index_fbjh .page-content .container-fluid .nbxc:nth-child(' + index + ')').fadeIn();
    });
}
function getUserName(userId) {
	var userName = getCookie('userName');
	if (userName == '' || userName == null ) {
        $.ajax({
            type:"GET",
            url:"http://localhost:8080/mm-ssm/user/query",
            dataType: "json",
            data:{
                id: userId
            },
            success: function (data) {
                $('#userMenu #userInfo').text('欢迎,' + data[0].name);
                setCookie('userName', data[0].name);
                setCookie('userDepartment', data[0].department);
                roleId = data[0].rolId;
                setCookie('roleId', roleId);
            },
            error: function (error) {
                alert("Request error!");
            }
        });
	} else {
        $('#userMenu #userInfo').text('欢迎,' + userName);
		return;
	}

}
function getLoginUserInfo() {
    userId = getCookie('userId');
    getUserName(userId);
    console.log('Welcome,' + userId);
}

function showIndexBdly(){
	var chart_index_bdly = echarts.init(document.getElementById('chart_index_bdly'),'macarons');
	var searchData = [1, 2, 3, 4, 5, 6, 7, 8];
	var countData = [];
    options_bdly = {
        title : {
            text: '八大领域工单统计图',
            // subtext: '测试数据',
            x:'center'
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        textStyle: {
            fontSize: 13
        },
        series : [
            {
                name: '工单数量',
                type: 'pie',
                radius : '50%',
                center: ['50%', '50%'],
                // roseType: "area",
                data:countData,
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    },
                    normal: {
                        label: {
                            show: true,
                            formatter:function(val){   //让series 中的文字进行换行
                                return val.name.split("-").join("\n");

                            }
                        }
                    }
                },
            }
        ]
    };
	//将八大领域的工单数查出，加入countData数组中
    $.ajax({
        url: "http://localhost:8080/mm-ssm/selfexamination/countByEightfieldsIndex",
        type: "POST",
        data: 'eightFieldsIndexs=' + searchData,
        success: function (data) {
            countData = [
                {value:data[0], name:'2017年党组巡视'},
                {value:data[1], name:'2018年省公司对-茂名供电局-“机动式”巡察'},
                {value:data[2], name:'五个专项治理、-五个专项行动'},
                {value:data[3], name:'其它巡视巡察'},
                {value:data[4], name:'扫雷行动'},
                {value:data[5], name:'红包专项治理'},
                {value:data[6], name:'正风反腐三年行动'},
                {value:data[7], name:'形式主义、官僚主义-专项治理'},
            ];
            options_bdly.series[0].data = countData;
            chart_index_bdly.setOption(options_bdly);
        },
        error: function (error) {
            console.log("Count error" + error.status);
        }
    });
}

function showIndexZrly(){
	var chart_index_zrly = echarts.init(document.getElementById('chart_index_zrly'),'macarons');

	options_zrly = {
		title : {
			text: '责任领域工单统计图',
			x:'center'
		},
		tooltip : {
			trigger: 'item',
			formatter: "{a} <br/>{b} : {c} ({d}%)"
		},
        textStyle: {
            fontSize: 13
        },
		series : [
			{
				name: '工单数量',
				type: 'pie',
				radius : '50%',
				center: ['50%', '50%'],
				// roseType: "area",
				data:[
					{value:335, name:'责任领域1'},
					{value:310, name:'责任领域2'},
					{value:234, name:'责任领域3'},
					{value:135, name:'责任领域4'},
					{value:1548, name:'责任领域5'},
					{value:457, name:'责任领域6'},
					{value:348, name:'责任领域7'},
					{value:627, name:'责任领域8'},
				],
				itemStyle: {
					emphasis: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					},
                    normal: {
                        label: {
                            show: true,
                            formatter:function(val){   //让series 中的文字进行换行
                                return val.name.split("-").join("\n");

                            }
                        }
                    }
				},
			}
		]
	};

    //
    $.ajax({
        url: "http://localhost:8080/mm-ssm/selfexamination/countByDomain",
        type: "POST",
        success: function (data) {
			var countData = [];
			for (var i = 0; i < data.length; i++) {
				var item = {};
				item.value = data[i].count;
				item.name = data[i].domain;
                countData.push(item);
			}
            options_zrly.series[0].data = countData;
            chart_index_zrly.setOption(options_zrly);
        },
        error: function (error) {
            console.log("Count error" + error.status);
        }
    });
}

function showIndexZrbm(){
	var chart_index_zrbm = echarts.init(document.getElementById('chart_index_zrbm'),'macarons');

	options_zrbm = {
		title : {
			text: '责任部门工单统计图',
			x:'center'
		},
		tooltip : {
			trigger: 'axis',
			// formatter: "{a} <br/>{b} : {c} ({d}%)"
		},
		// legend: {
		// 	orient: 'vertical',
		// 	left: 'left',
		// 	data: ['领域1','领域2','领域3','领域4','领域5','领域6','领域7','领域8']
		// },
		toolbox: {
	        show : true,
	        feature : {
	            mark : {show: true},
	            dataView : {show: true, readOnly: false},
	            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        },
	        iconStyle: {
                borderColor: '#1d83e6',
			}
	    },
		calculable : true,
		xAxis : [
	        {
	            type : 'category',
	            boundaryGap : true,
	            data : []
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value'
	        }
	    ],
	     grid: {
	        left: '3%',
	        right: '4%',
	        containLabel: true
	    },
	    dataZoom: [{
	        type: 'inside',
	        start: 0,
	        end: 100,
	    }, {
	        start: 74,
	        end: 100,
	        handleSize: '80%',
	        handleStyle: {
	            color: '#fff',
	            shadowBlur: 3,
	            shadowColor: 'rgba(0, 0, 0, 0.6)',
	            shadowOffsetX: 2,
	            shadowOffsetY: 2
	        }
	    }],
		series : [
			{
				name: '工单数量',
				type: 'bar',
				// radius : ['35%', '110%'],
				// center: ['50%', '60%'],
				// roseType: "area",
	            stack: '总量',
	            barMaxWidth : 30,
	            data:[],
				itemStyle: {
					normal: {
                        color: '#1d83e6',
					},
					emphasis: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}
		]
	};

    $.ajax({
        url: mmssm_url + "selfexamination/countByDepartment",
        type: "POST",
        success: function (data) {
            var countData = [];
            var departmentData = [];
            for (var i = 0; i < data.length; i++) {
                countData.push(data[i].count);
                departmentData.push(data[i].department);
            }
            options_zrbm.xAxis[0].data = departmentData;
            options_zrbm.series[0].data = countData;
            chart_index_zrbm.setOption(options_zrbm);
        },
        error: function (error) {
            console.log("Count error" + error.status);
        }
    });
}

$(function() {
    getLoginUserInfo();

    //注销当前登录
    $('.logOut').click(function () {
        $.ajax({
            type:"POST",
            url: mmssm_url + "logout",
            dataType: "json",
            success: function () {
                delCookie('userId');
                delCookie('userName');
                delCookie('userDepartment');
                window.location.href = mmssm_url + 'static/html/newsPage.html';
            },
            error: function (error) {
                alert("注销失败");
            }
        });
    });
});